var requests = require("../../utils/requests.js")
var formid = require("../../utils/getformid.js")
var app = getApp();
var souceUrl = app.globalData.source;
var hongbaointerval
var bannertextinter
var from_userid;
var inter;
var haveloaddata;
var cangetHongbao;
var sign = false;
var showsigntoady = false;
Page({
  data: {
    authbtn: false,
    qianzui: getApp().globalData.source,
    collectnetimg: getApp().globalData.source + "details/pop.png",
    imgUrls: [],
    imgUrls2: [],
    swiperCurrent2: 0,
    showequipment: true,
    showplay: true,
    homedata: [],
    showbanner: true,
    playimg: "",
    hotlisten: [],
    showhongbaoicon: false,
    showhongbao: false,
    hongbaodata: {},
    indicatorDots: false,
    indicatorDots2: false,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 5000,
    clickhide: false,
    duration: 500,
    indicatorColor: '#EAEAEA',
    indicatorActiveColor: '#ffffff',
    swiperIndex: 0,
    info: {},
    showhot: true,
    navigationData: [],
    collectshow: false,
    barrageList1: [],
    scroll_top: 0,
    winH: 0,
    showAuth: false,
    userIdss: "", //用户编号
    homeBannerValue: "", //首页banner记录
    homeNavigationBarId: "", //首页导航栏bar,Id记录
    homeNavigationBarName: "", //首页导航栏bar,Name记录 
    homeClassifyProgramId: "", //热听榜等栏目点击Id记录
    homeClassifyProgramName: "", //热听榜等栏目点击Name记录
    homeClassifyId: "", //分类id
    homeClassifyName: "", //分类名称
    signonshow: false,
    signonpopbg: getApp().globalData.source + "sign_in/sign-on-pop-bg.png",
    authbg: getApp().globalData.authImg,
    authbtn2: getApp().globalData.source + "red_packet/btn2.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    dingshihongbaoshow: false,
    dingshihongbao: getApp().globalData.source + "dialog/dingshihongbao.png",
  },
  jumptotal: function() {
    wx.navigateTo({
      url: '../my/mydetail/mydetail',
    })
    this.setData({
      showhongbao: false,
      showhongbaoicon: false
    })
  },
  signoutside: function() {
    this.setData({
      signonshow: false
    })
  },
  signinside: function() {},

  closePopUp: function() {
    var that = this;
    this.setData({
      dingshihongbaoshow: false
    })
  },
  //轮播图的切换事件 
  swiperChange2: function(e) {
    console.log(e);
    this.setData({
      swiperCurrent2: e.detail.current //获取当前轮播图片的下标
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.onShow()
    setTimeout(function() {
      wx.stopPullDownRefresh()
    }, 2000)
  },

  signOn: function() {
    wx.navigateTo({
      url: '../sign_on/sign_on',
    })
  },
  /**
   * 点击分类跳转到列表页
   */
  classifyBindtap: function(e) {
    var that = this;
    //获取推送消息fromID
    var id = e.currentTarget.dataset.id;
    var classify = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: "../home/classify/classify?id=" + id + "&classify=" + classify,
      success: function() {},
      fail: function() {}
    })
  },

  tobannerdetails: function(e) {
    var vm = this
    var index = e.currentTarget.dataset.index;
    var bn = vm.data.imgUrls[index]
    //统计数据埋点
    vm.setData({
      userIdss: wx.getStorageSync("userId"), //用户编号
      homeBannerValue: bn.cSrc, //首页banner 栏目id，如果是H5就是H5连接地址，如果是栏目就是Id记录 
    })
    if (bn.isH5 == 1) {
      //跳转原生详情页 
      wx.navigateTo({
        url: "../day_day_listen/details/details?id=" + bn.cSrc + "&season=" + 1,
        success: function() {},
        fail: function() {}
      })
    } else if (bn.isH5 == 0) {
      //跳转h5详情页
      wx.navigateTo({
        url: "../webview/webview?url=" + bn.cSrc,
        success: function() {},
        fail: function() {}
      })
    } else {
      wx.navigateTo({
        url: bn.cSrc,
        success: function() {},
        fail: function() {}
      })
    }
  },


  tobannerdetails2: function(e) {
    var vm = this
    var index = e.currentTarget.dataset.index;
    var bn = vm.data.imgUrls2[index]
    //统计数据埋点
    vm.setData({
      userIdss: wx.getStorageSync("userId"), //用户编号
      homeBannerValue: bn.cSrc, //首页banner 栏目id，如果是H5就是H5连接地址，如果是栏目就是Id记录 
    })
    if (bn.isH5 == 1) {
      //跳转原生详情页 
      wx.navigateTo({
        url: "../day_day_listen/details/details?id=" + bn.cSrc + "&season=" + 1,
        success: function() {},
        fail: function() {}
      })
    } else if (bn.isH5 == 0) {
      //跳转h5详情页
      wx.navigateTo({
        url: "../webview/webview?url=" + encodeURIComponent(bn.cSrc),
        success: function() {},
        fail: function() {}
      })
    } else {
      if ("/pages/welfare_bar/welfare_bar" == bn.cSrc) {
        wx.switchTab({
          url: bn.cSrc,
          success: function() {},
          fail: function() {}
        })
      } else {
        wx.navigateTo({
          url: bn.cSrc,
          success: function() {},
          fail: function() {}
        })
      }

    }
  },
  closeredpockets: function() {
    this.setData({
      showhongbao: false,
    })
  },

  /**
   * 跳转到播放详情页面
   */
  todetails: function(e) {
    this.commitformid(e)
    var season = e.currentTarget.dataset.season;
    var id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.title; //节目标题 
    var vm = this
    //热听绑定、有声小说等、、、点击埋点 
    vm.setData({
      userIdss: wx.getStorageSync("userId"), //用户编号
      homeClassifyProgramId: id, //热听榜等。。栏目点击Id记录
      homeClassifyProgramName: title, //热听榜。。等栏目点击Name记录
    })
    wx.navigateTo({
      url: "../day_day_listen/details/details?id=" + id + "&season=" + season,
      success: function() {},
      fail: function() {}
    })
  },

  addFormId: function(formId) {
    //加载首页数据 
    var data = {
      formId: formId,
      userId: wx.getStorageSync("userId")
    };
    getApp().request(getApp().globalData.https + "customer/save/formId", //处理获取分享群信息
      "post", data,
      function(res) {
        if (res.code == 0) {}
      },
      function(res) {}
    )
  },


  gethotdata: function() {
    var that = this;
    var dataParm;
    if (wx.getStorageSync("userId") == undefined || wx.getStorageSync("userId") == '') {
      dataParm = {
        categoryId: "41",
        startPoint: "1",
        maxPage: "3",
      }
    } else {
      dataParm = {
        categoryId: "41",
        startPoint: "1",
        maxPage: "3",
        userId: wx.getStorageSync("userId")
      }
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/program/41",
      "get", dataParm, "加载中...",
      function(res) {
        if (res.code == 0) {
          that.setData({
            hotlisten: res.data.data
          });
        }
      },
      function(res) {
        //   console.log(res)
      }
    )
  },
  toactivitydetails: function() {
    this.setData({
      dingshihongbaoshow: false
    })
    wx.switchTab({
      url: '/pages/welfare_bar/welfare_bar',
    })

  },
  getdata: function() {
    var that = this;
    var data;
    if (wx.getStorageSync("platform") != "0") {
      data = {
        "userId": wx.getStorageSync("userId")
      }
    } else {
      data = {
        "userId": wx.getStorageSync("userId"),
        "platform": wx.getStorageSync("platform"),
      }
    }

    getApp().request(getApp().globalData.https + "programResource/AllCategoryProgram",
      "get", data,
      function(res) {
        if (res.code == 0) {
          haveloaddata = true;
          var data = res.data;
          var newdata = [];
          for (var i = 0; i < data.length; i++) {
            var iphone = wx.getStorageSync("iPhone");
            if (iphone != "-1") {
              if (data[i].id == "51" || data[i].id == "43" || data[i].id == "44" || data[i].id == "45") {
                newdata.push(data[i]);
              }
            } else {
              if (data[i].id != "49") {
                newdata.push(data[i]);
              }
            }
          }
          that.setData({
            homedata: newdata
          });
        }
      },
      function(res) {}
    )
  },


  //正在收听按钮
  onXuanfuButtonClick: function() {
    var programid = wx.getStorageSync("programid");
    wx.navigateTo({
      url: "../day_day_listen/details/details?id=" + programid + "&season=" + 1 + "&url=" + undefined,
      success: function() {},
      fail: function() {}
    })
  },

  //加载首页导航栏列表
  findNavigationAircleList: function() {
    var that = this;
    getApp().request(getApp().globalData.https + "navigationCircle/findNavigationCircleList",
      "get", "",
      function(res) {
        if (res[0].code == 0) {
          var iphone = wx.getStorageSync("iPhone");
          if (iphone != "-1") {
            that.setData({
              navigationData: [],
              http: app.globalData.source
            })
          } else {
            let nv = res[0].list
            for (var i = 0; i < nv.length; i++) {
              nv[i].icon = getApp().globalData.source + nv[i].icon
            }
            that.setData({
              navigationData: nv,
              http: app.globalData.source
            })
          }

        }
      },
      function(res) {}
    )
  },

  checklogin: function () {
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      if (wx.getStorageSync("authtype") == "0") {
        this.setData({
          showAuth: true,
          showAuth2: false
        })
      } else {
        this.setData({
          showAuth: false,
          showAuth2: true
        })
      }
      return true
    } else {
      this.setData({
        showAuth: false,
        showAuth2: false
      })
      return false
    }
  },
  // banner下 五个按钮跳转
  classitemclick: function(e) {
    var that = this;
    this.commitformid(e)
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var navigationData = that.data.navigationData;
    for (var i = 0; i < navigationData.length; i++) {
      let nv = navigationData[i];
      if (nv.id == id) {
        that.setData({
          userIdss: wx.getStorageSync("userId"),
          homeNavigationBarId: nv.id, //首页导航栏bar,Id记录
          homeNavigationBarName: nv.name, //首页导航栏bar,Name记录
        })
        // if (nv.url =="/pages/hope/hope?id=49"){
        //   if (this.checklogin()) return
        // }
        wx.navigateTo({
          url: nv.url + "&classify=" + nv.name,
        })
      } else {
        console.log("未知错误")
      }
    }
  },
  /**
   * 搜索框跳转
   */
  search: function() {
    wx.navigateTo({
      url: "../search/search_result/search_result",
      success: function() {},
      fail: function() {}
    })
  },
  // 轮播滑动时，获取当前的轮播id
  swiperChange(e) {
    var that = this;
    this.setData({
      swiperIndex: e.detail.current,
    })
  },
  // 收藏显示
  collectShow: function() {
    var that = this
    this.setData({
      collectshow: true
    })
  },

  // 收藏关闭
  collectHide: function() {
    var that = this
    this.setData({
      collectshow: false
    })
  },

  // 弹幕
  // scroll: function(e) { 
  //   this.setData({
  //     scroll_top: e.detail.scrollTop
  //   })
  // },

  //判断是否签到
  checkIsSignOn: function() {
    if (showsigntoady) {
      return
    }
    var iphone = wx.getStorageSync("iPhone");
    if (iphone != "-1") {
      return
    }
    var vm = this
    var data = {
      userId: wx.getStorageSync("userId")
    };
    getApp().request(getApp().globalData.https + "activityResource/currentDaySignIn",
      "get", data,
      function(res) {
        if (res.code == 0) {
          if (res.data.currentDaySignIn == "0") {
            vm.getSignInfo();
          } else {
            vm.setData({
              signonshow: false
            })
          }

        }
      },
      function(res) {}
    )
  },

  //本周签到情况
  getSignInfo: function() {
    var vm = this
    var data = {
      userId: wx.getStorageSync("userId"),
      flg: "0"
    };
    getApp().request(getApp().globalData.https + "activityResource/signInList",
      "get", data,
      function(res) {
        if (res.code == 0) {
          var signinfo = res.data[0].subSignInBo;
          var signtop = [];
          var signbottom = [];
          // for (var i = 0; i < signinfo.length; i++) {
          //   if (i <= 3) {
          //     signtop.push(signinfo[i]);
          //   } else {
          //     signbottom.push(signinfo[i]);
          //   }
          // }
          showsigntoady = true;
          vm.setData({
            signonshow: true,
            signtop: signinfo,
            signbottom: signbottom
          })

        }
      },
      function(res) {}
    )
  },
  signover: function() {
    this.setData({
      signonshow: false
    })
  },
  //点击签到
  sign_today: function() {
    if (sign) {
      return
    }
    sign = true;
    var vm = this
    var data = {
      userId: wx.getStorageSync("userId"),
    };
    getApp().request(getApp().globalData.https + "activityResource/signInRecord",
      "get", data,
      function(res) {
        if (res.code == 0) {
          //签到提醒
          // vm.getSignInfo();
          getApp().showMsgToast('送您' + res.data.balance + "听币");
          vm.setData({
            signonshow: false,
          })
        } else {
          getApp().showMsgToast("已签到");
        }
      },
      function(res) {}
    )
  },
  onShow: function() {
    cangetHongbao = true;
    this.setData({
      autoplay: true
    })
    var that = this
    //检测是否有红包
    this.checkhongbao();
    this.getdetails();
    // 检测非正常退出时音乐播放状态
    this.checkmusicstate()
    var iphone = wx.getStorageSync("iPhone");
    if (iphone == "-1") {
      that.setData({
        showhot: true
      })
    } else {
      that.setData({
        showhot: false
      })
    }
    if (this.data.homedata == undefined || this.data.homedata.length == 0) {
      this.gethotdata()
      setTimeout(function() {
        that.getdata();
      }, 500)
    }
    if (this.data.navigationData[0] == undefined) {
      this.findNavigationAircleList()
    }

    if (this.data.imgUrls[0] == undefined) {
      this.getbanner()
    }

    if (this.data.imgUrls2[0] == undefined) {
      this.getbanner2()
    }

    if (wx.getStorageSync("userId") != "" && wx.getStorageSync("userId") != undefined) {
      this.setData({
        showAuth: false,
        showAuth2: false
      })
    }


    // this.getbannertext()
    this.checkIsSignOn();

  },
  //检测是否首次登陆
  checkfirstLogin: function() {
    var that = this
    var iphone = wx.getStorageSync("iPhone");
    var firstAuth = wx.getStorageSync("firstAuth");
    if (iphone != "1") {
      if (firstAuth == "1") {
        setTimeout(function() {
          that.setData({
            dingshihongbaoshow: true
          })
        }, 10 * 1000)
        wx.setStorageSync("firstAuth", "-1")
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var userid = options.userId;
    if (userid != undefined) {
      wx.setStorageSync("fromid", userid)
    } else {
      wx.setStorageSync("fromid", "-2")
    }
    var channel = options.channel;
    if (channel != undefined) {
      wx.setStorageSync("channel", channel)
    }
    from_userid = options.userId
    var that = this;
    this.getequipment()
    // 检测是否签到
    this.checkfirstLogin()
  },

  getbanner: function() {
    var that = this;
    //加载首页banner数据
    var data = {
      "type": 0,
      "platform": wx.getStorageSync("platform")
    }
    app.requestLoading(app.globalData.https + "programResource/commonBannerList",
      "get", data, "加载中...",
      function(res) {
        if (res.code == 0) {
          // 获取系统信息 
          var data = res.data;
          var newdata = [];
          for (var i = 0; i < data.length; i++) {
            newdata.push(data[i]);
          }
          that.setData({
            imgUrls: newdata,
          });
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },
  getbanner2: function() {
    var that = this;
    //加载首页banner数据
    var data = {
      "type": 10,
      "platform": wx.getStorageSync("platform")
    }
    app.requestLoading(app.globalData.https + "programResource/commonBannerList",
      "get", data, "加载中...",
      function(res) {
        if (res.code == 0) {
          // 获取系统信息 
          var data = res.data;
          var newdata = [];
          if (res.data.length == 0) {
            that.setData({
              showbanner: false
            })
          }
          for (var i = 0; i < data.length; i++) {
            var iphone = wx.getStorageSync("iPhone");
            if (iphone != "-1") {
              that.setData({
                showbanner: false
              })
            } else {
              newdata.push(data[i]);
            }
          }
          that.setData({
            imgUrls2: newdata,
          });
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },
  getequipment: function() {
    var that = this;
    //是否显示维护中
    app.requestLoading(app.globalData.https + "/userResource/remind/0",
      "get", "", "加载中...",
      function(res) {
        if (res.code == 0) {
          if (res.data.isFalse == getApp().globalData.isMaintain) {
            wx.showModal({
              showCancel: false,
              title: '更新提示',
              content: '系统正在维护中，请耐心等待;',
            })
          }
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },
  // getbannertext: function() {
  //   var that = this;
  //   //加载首页banner数据
  //   app.request(app.globalData.https + "programResource/scrolTextList",
  //     "get", "",
  //     function(res) {
  //       if (res.code == 0) {
  //         // 获取系统信息  
  //         that.setData({
  //           barrageList1: res.data,
  //         });
  //       }
  //     },
  //     function(res) {
  //       console.log(res)
  //     }
  //   )
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },


  /**
   * 检测非正常退出时音乐播放状态
   */
  checkmusicstate: function() {
    console.log("playstatus" + wx.getStorageSync("playstatus"))
    var that = this
    //根据音乐状态 控制图片是否旋转
    if (wx.getStorageSync("playstatus") == 1) {
      that.setData({
        animationplay: true
      })
    } else {
      that.setData({
        animationplay: false
      })
    }
  },


  /**
   * 是否显示正在收听按钮
   */
  showonListen: function() {
    var programid = wx.getStorageSync("programid");
    if (programid == undefined || programid == '') {
      this.setData({
        showplay: false
      })
    } else {
      this.setData({
        showplay: true
      })
    }
  },

  /**
   * 红包 、正在听动画
   */
  animation: function() {
    var that = this
    inter = setInterval(function() {
      that.setData({
        clickhide: !that.data.clickhide
      })
    }, 250)
  },


  /**
   * 获取收听历史记录详情
   */
  getdetails: function() {
    var playimg = wx.getStorageSync("playimg");
    if (playimg != "" && playimg == undefined) {
      this.setData({
        playimg: playimg
      })
    }
    var vm = this
    var data = {
      "startPoint": 1,
      "maxPage": 1,
    }
    var programid = wx.getStorageSync("programid")
    if (programid == '' || programid == undefined) {
      vm.setData({
        showplay: false
      })
      return
    }
    var userIds = wx.getStorageSync("userId") === "" ? -1 : wx.getStorageSync("userId");
    getApp().request(getApp().globalData.https + "programResource/programDetail/" + programid + "/" + userIds,
      "get", data,
      function(res) {
        if (res.code == 0) {
          vm.setData({
            showplay: true
          })
          vm.setData({
            info: res.data,
            playimg: res.data.shareImageUrl
          })
        } else {
          vm.setData({
            showplay: false
          })
        }
      },
      function(res) {
        vm.setData({
          showplay: false
        })
      });
  },

  openhongbao: function() {
    if (!cangetHongbao) {
      return
    }
    cangetHongbao = false;
    this.setData({
      showhongbao: true,
      showhongbaoicon: false
    })
    //关闭红包计时器
    if (inter != null || inter != undefined) {
      clearInterval(inter);
    }
    //领取红包
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId"),
      "state": 1,
      "tb": vm.data.hongbaodata.tb
    }
    getApp().request(getApp().globalData.https + "hd/listen/classify/random/savetb",
      "post", data,
      function(res) {},
      function(res) {});
  },
  //检测该页面是否有红包显示
  checkhongbao: function() {
    var iphone = wx.getStorageSync("iPhone");
    if (iphone != "-1") {
      return
    }
    var vm = this
    var data = {
      "pageConfig": "首页",
      "userId": wx.getStorageSync("userId")
    }
    getApp().request(getApp().globalData.https + "hd/listen/classify/random",
      "post", data,
      function(res) {
        //state=1时,显示红包就开始倒计时，隐藏掉红包入口
        if (res.code == 0) {
          if (res.data.state == 1) {
            var time = 15
            vm.setData({
              showhongbaoicon: true,
              hongbaodata: res
            })
            // 红包动画
            vm.animation();
            setTimeout(function() {
              vm.setData({
                showhongbaoicon: false
              })
              if (inter != null || inter != undefined) {
                clearInterval(inter)
              }
            }, 15000)
          } else {
            vm.setData({
              showhongbaoicon: false
            })
          }
        }

      },
      function(res) {});
  },

  commitformid: function(e) {
    var that = this;
    //获取推送消息fromID
    let formId = e.detail.formId;
    // console.log('form发生了submit事件，推送码为：', formId)
    var url = "";
    formid.dealFormIds(formId, url);
    //调用接口将formid + 用户id + 过期时间 保存到数据库中TODO。。。
    if (wx.getStorageSync("userId") != "" && wx.getStorageSync("userId") != undefined) {
      that.addFormId(formId)
    }
  },

  formcommitmore: function(e) {
    this.commitformid(e);
    var id = e.currentTarget.dataset.id;
    var classify = e.currentTarget.dataset.title;
    let that = this;
    that.setData({
      userIdss: wx.getStorageSync("userId"), //用户编号
      homeClassifyId: id,
      homeClassifyName: classify
    })
    wx.navigateTo({
      url: "../home/classify/classify?id=" + id + "&classify=" + classify,
      success: function() {},
      fail: function() {}
    })
  },
  authbtn: function() {
    var vm = this
    wx.showLoading({
      title: "正在检查网络.."
    })
    this.setData({
      authbtn: true
    })
  },
  bindGetUserInfo: function(e) {
    app.authInfo(e);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    if (bannertextinter != null) {
      clearInterval(bannertextinter);
    }

    if (inter != null) {
      clearInterval(inter);
    }
    this.setData({
      autoplay: false
    })
  },
})